package be.bejug.scrumadmin.components.panels;

import java.util.Set;
import java.util.TreeSet;

import org.springframework.beans.factory.annotation.Autowired;

import be.bejug.scrumadmin.components.TaskCard;
import be.bejug.scrumadmin.domain.Sprint;
import be.bejug.scrumadmin.domain.Story;
import be.bejug.scrumadmin.domain.Task;
import be.bejug.scrumadmin.domain.enums.Status;
import be.bejug.scrumadmin.services.SprintService;
import be.bejug.scrumadmin.spring.ApplicationHolder;
import be.bejug.scrumadmin.spring.Injector;

import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Panel;

/**
 * 
 * @author Glenn Dejaeger
 * 
 */
@SuppressWarnings("serial")
public class SprintTaskPanel extends AbstractTab {

	@Autowired
	private transient SprintService sprintService;

	Panel todoPanel, inProgressPanel, donePanel;

	/**
	 * 
	 */
	public SprintTaskPanel() {
		Injector.inject(this);
		initComponents();
	}

	private void initComponents() {
		HorizontalLayout horizontalLayout = new HorizontalLayout();

		todoPanel = new StatusPanel(
				ApplicationHolder.getMessage("taskboard.todo.label"));

		inProgressPanel = new StatusPanel(
				ApplicationHolder.getMessage("taskboard.inprogress.label"));

		donePanel = new StatusPanel(
				ApplicationHolder.getMessage("taskboard.done.label"));

		horizontalLayout.addComponent(todoPanel);
		horizontalLayout.addComponent(inProgressPanel);
		horizontalLayout.addComponent(donePanel);
		horizontalLayout.setExpandRatio(todoPanel, 2.0f);
		horizontalLayout.setExpandRatio(inProgressPanel, 1.5f);
		horizontalLayout.setExpandRatio(donePanel, 2.0f);
		horizontalLayout.setSizeFull();
		horizontalLayout.setSpacing(true);

		addComponent(horizontalLayout);
	}

	@Override
	protected String getCaptionKey() {
		return "panel.title.task";
	}

	@Override
	protected void loadData() {
		Sprint sprint = sprintService.getCurrentSprint();
		TreeSet<Story> stories = new TreeSet<Story>(sprint.getStories());
		createCards(stories);
	}

	private void createCards(final Set<Story> stories) {
		for (Story story : stories) {
			TreeSet<Task> tasks = new TreeSet<Task>(story.getTasks());
			for (Task task : tasks) {
				TaskCard taskCard = new TaskCard(task);

				if (Status.TODO == task.getStatus()) {
					todoPanel.addComponent(taskCard);
				} else if (Status.IN_PROGRESS == task.getStatus()) {
					inProgressPanel.addComponent(taskCard);
				} else if (Status.DONE == task.getStatus()) {
					donePanel.addComponent(taskCard);
				}
			}
		}
	}
}
